const express = require('express')
const router = express.Router()
const userModel = require('./../model/userModel')

// 新增
router.post('/api/user', async (req, res) => {
  const userInfo = req.query
  let data = {
    code: 0,
    msg: ''
  }
  if (userInfo.account) {
    if (userInfo.passwd) {
      const hasUser = await userModel.findOne({
        account: userInfo.account
      })
      if (hasUser) {
        data.msg = '账号已存在'
        res.send(data)
      } else {
        const userJudg = await userModel.create({
          account: userInfo.account,
          passwd: userInfo.passwd
        })
        if (userJudg) {
          data.msg = 'succeed'
          data.data = true
          data.code = 1
          res.send(data)
        }
      }
    } else {
      data.msg = '密码不存在'
      res.send(data)
    }
  } else {
    data.msg = '账号不存在'
    res.send(data)
  }
})

// 修改
router.put('/api/user', async (req, res) => {
  const userInfo = req.query
  let data = {
    code: 0,
    data: false,
    msg: '更新失败'
  }
  if (userInfo.accountId) {
    const hasUser = await userModel.findOne({
      account: userInfo.account
    })
    if (hasUser) {
      data.msg = '账号名已存在,请更改账号'
      res.send(data)
    } else {
      const userJudg = await userModel.updateOne(
        {
          accountId: userInfo.accountId
        },
        {
          $set: {
            account: userInfo.account,
            passwd: userInfo.passwd
          }
        }
      )
      if (userJudg) {
        data.msg = 'succeed'
        data.data = true
        data.code = 1
        res.send(data)
      } else {
        res.send(data)
      }
    }
  } else {
    data.msg = '获取不到accountId'
    res.send(data)
  }
})

// 删除
router.delete('/api/user', async (req, res) => {
  const userInfo = req.query
  let data = {
    code: 0,
    data: false,
    msg: '删除失败'
  }
  if (userInfo.ids) {
    const idsArr = userInfo.ids.split(',')
    for (let index = 0; index < idsArr.length; index++) {}
    const delUser = await userModel.remove({
      accountId: { $in: idsArr }
    })
    if (delUser) {
      data.msg = 'succeed'
      data.data = true
      data.code = 1
      res.send(data)
    } else {
      res.send(data)
    }
  } else {
    data.msg = '获取不到accountId'
    res.send(data)
  }
})

// 查找用户
router.get('/api/user', async (req, res) => {
  const userInfo = req.query
  let data = {
    code: 0,
    data: false,
    msg: '查找失败'
  }
  const page = Number(userInfo.page)
  const size = Number(userInfo.size)
  userModel
    .find({})
    .skip(page * size)
    .limit(size)
    .sort({ id: -1 })
    .exec((err, doc) => {
      if (!err) {
        data.data = doc
        data.msg = true
        res.send(data)
      } else {
        data.msg = err
        res.send(data)
      }
    })
})
module.exports = router
